/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fr.unice.miage.m2.webservices.cl.xbay.tools;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Utilisateur
 */
public abstract class Tools {

    public static String captureUrlImage(String destDir, String storFile, String distantImgUrl) {
        InputStream is = null;
        try {
            String localUrl;
            URL url = new URL(distantImgUrl);
            System.out.println("########### Downloading the cover from : " + url.getPath());
            is = url.openStream();

            String type = ".png";
            File file = new File(destDir, storFile+type);
            System.err.println("absolute path cover_url : " + file.getAbsolutePath());
            localUrl = file.getAbsolutePath();

            OutputStream os = new FileOutputStream(file);
            byte buf[] = new byte[1024];
            int len;
            while ((len = is.read(buf)) > 0) {
                os.write(buf, 0, len);
            }
            os.close();
            is.close();

            return localUrl;

        } catch (IOException ex) {
            Logger.getLogger(Tools.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                is.close();
            } catch (IOException ex) {
                Logger.getLogger(Tools.class.getName()).log(Level.SEVERE, null, ex);
            }
            return null;
        }

    }
}
